package com.db.chat;



import java.io.*;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicInteger;

import static java.lang.Thread.sleep;

public class SimpleTestClient {
    private static final String VERY_LONG_LINE =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefjhijklmnopqrstuvwxyz" +
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefjhijklmnopqrstuvwxyz" +
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefjhijklmnopqrstuvwxyz";

    private static AtomicInteger idCounter = new AtomicInteger(0);

    private int id = idCounter.getAndIncrement();
    private String name = "Client-" + id;
    private int sleepTimeInMsec;

    public SimpleTestClient(int sleepTimeInMsec, int commandNumber) {
        this.sleepTimeInMsec = sleepTimeInMsec;
        try(
            Socket s = new Socket("localhost", 10002);
            DataOutputStream os = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));
            DataInputStream is = new DataInputStream(new BufferedInputStream(s.getInputStream()))
        ) {
            execute(os, is, "/chid " + name);
            for (int i = 0; i < commandNumber; i++) {
                if (i % 100 == 0) {
                    execute(os, is, "/hist");
                    continue;
                }
                if (i % 10 == 0) {
                    execute(os, is, "/chid SameName");
                    continue;
                }
                if (i % 15 == 0) {
                    execute(os, is, "/chroom testRoom" + i);
                }
                if (i % 12 == 0) {
                    execute(os, is, "/snd " + VERY_LONG_LINE);
                    continue;
                }
                execute(os, is, "/snd message" + i);
            }

        } catch (InterruptedException e) {
            System.out.println("Interrupted exception");
        } catch (IOException e) {

            System.out.println("IO exception");
        }
    }

    private void execute(DataOutputStream os, DataInputStream is, String command) throws IOException, InterruptedException {
        System.out.println(command);
        os.writeUTF(command);
        os.flush();
        sleep(sleepTimeInMsec);
        int result = 0;
        while (is.available() > 0) {
            is.readUTF();
            result++;
            //System.out.println(is.readUTF());
            System.out.println(name + " received " + result + " messages");
        }
    }
}
